/**
 * Created by Administrator on 2017/7/20.
 */
(function() {
    "use strict";
    var app = angular.module("angularApp");

    app.controller('ruleCtrl', function ($scope,$rootScope, $http,$uibModal,$stateParams,fac, $q,$interval) {

            $scope.checkAll = $rootScope.checkAll;
            $scope.allChecked = $rootScope.allChecked;
            $scope.unCheckAll  = $rootScope.unCheckAll;
            $scope.checkOne  = $rootScope.checkOne;
            $scope.showPhoto  = $rootScope.showPhoto;
            $scope.processImgUrl  = $rootScope.processImgUrl;
            $scope.hasChecked  = $rootScope.hasChecked;

            $scope.curInstance  = $scope.$parent.search.curInstance;

            $scope.listDicts = function(element){
                return $scope.curInstance.dictTypeList.find(function(n){return n.id == element}).data;
            }

            $scope.addDict = function(type){
                type.data = type.data||[];
                var item = {edit:true,copy:{instanceId:$scope.curInstance.id,element:type.id}};
                type.data.splice(0,0,item);
                //type.data.push(item);
            };
            $scope.editDict = function(item){
                item.copy = angular.extend({},item);
                item.edit = true;
            };
            $scope.cancelDict = function(type,item){
                if(!item.id){
                    type.data.splice(type.data.indexOf(item), 1)
                }else{
                    delete item.copy;
                    item.edit = false;
                }
            };

            $scope.saveDict = function (form,item,url) {
                form.$setSubmitted(true);
                if (!form.$valid) {
                    return;
                }
                $http.post(url, item.copy).success(function (resp, status, headers, config) {
                    if (resp.code === 0) {
                        $.extend(item,resp.data);
                        item.edit = false;
                        msg("保存成功!");
                    } else {
                        alert(resp.msg);
                    }
                })
            }
            $scope.delDict = function (type,item,table) {
                var search = {currentPage:1,pageSize:1,instanceId:$scope.curInstance.id,dictType:type.id,dictId:item.id}
                fac.getPageResult("../dict/dictReference",search,function(pageModel){
                    item.pageModel = pageModel;
                    if(pageModel.data.length>0){
                        alert("此样式函数有被引用，请勿删除！");
                    }else{
                        confirm("确认删除该样式函数吗？",function(){
                            $http.get("../dict/del", {params:{ids:item.id,table:table}}).success(function (resp, status, headers, config) {
                                if (resp.code === 0) {
                                    type.data.splice(type.data.indexOf(item),1);
                                    msg("删除成功!");
                                } else {
                                    alert(resp.msg);
                                }
                            })
                        });
                    }
                });
            }

            //查看样式函数引用
            $scope.dictReference = function(type,item){

                if($scope.search.curDict && $scope.search.curDict.id == item.id){
                    delete $scope.search.curDict;
                    return;
                }
                $scope.search.curDict = item;
                $scope.search.curDict.type = type.id;
                delete item.pageModel;
                var search = {currentPage:1,pageSize:10000,instanceId:$scope.curInstance.id,dictType:type.id,dictId:item.id}
                fac.getPageResult("../dict/dictReference",search,function(pageModel){
                    item.pageModel = pageModel;
                });
            }


            $scope.addRule = function(style){
                style.data = style.data||[];
                var item = {edit:true,copy:{instanceId:$scope.curInstance.id,styleTypeId:style.id}};
                style.data.push(item);
            };



        //添加与保存instance
        $scope.copyStyle = function(dict,style){
            var modal = $uibModal.open({
                animation: false,
                size:'',
                templateUrl: 'view/instance/style_copy.modal.html',
                controller: 'styleCopyModalCtrl'
                ,resolve: {dict: function(){return dict},style: function(){return style},curInstance:function(){return $scope.curInstance}}
            });
            modal.result.then(function (data) {
                if(data.instanceId && data.instanceId != data.oldInstanceId){
                   var instance = $rootScope.instanceCache.find(function(n){return n.id == data.instanceId});
                   if(instance){
                       delete  instance.elementList;
                       $rootScope.instanceCache.splice($rootScope.instanceCache.indexOf(instance),1);
                       /*var element = instance.elementList.find(function(n){return n.id == data.element});
                       if(element.rowStyles && element.rowStyles.length){
                           var style = element.rowStyles.find(function(n){return n.id == data.styleId});
                           $scope.queryRule(data.instanceId,element,style);
                       }*/
                   }
                    /*if($scope.temp.instance.id == curInstance.id){
                        var search = {currentPage:1,pageSize:20,instanceId:curInstance.id,element:dict.id,styleTypeId:$scope.temp.style.id}
                        fac.getPageResult("../rule/list",search,function(resp){
                            $scope.temp.style.data = resp.data;
                        });
                    }*/
                }
            }, function () {
                console.info('Modal dismissed at: ' + new Date());
            });
        };

            $scope.editRule = function(item){
                item.copy = angular.extend({},item);
                item.edit = true;
            };
            $scope.cancelRule = function(style,item){
                if(!item.id){
                    style.data.splice(style.data.indexOf(item), 1)
                }else{
                    delete item.copy;
                    item.edit = false;
                }
            };

            $scope.saveRule = function (form,item,url,style) {
                if(!checkScales(style)){
                    return;
                }
                form.$setSubmitted(true);
                if (!form.$valid) {
                    return;
                }
                $http.post(url, item.copy).success(function (resp, status, headers, config) {
                    if (resp.code === 0) {
                        $.extend(item,resp.data.rule);
                        if(resp.data.textStyleType && resp.data.textStyleType.id){
                            //生成了文样样式：
                            var textStyleType = resp.data.textStyleType;
                            style.textTypeId =textStyleType.id;
                            style.textName = textStyleType.name;
                            style.textStyleID = textStyleType.code;
                        }
                        item.edit = false;
                        msg("保存成功!");
                    } else {
                        alert(resp.msg);
                    }
                })
            }
            $scope.delRule = function (style,item) {
                confirm("确认删除该样式规则吗？",function(){
                    $http.get("../rule/del", {params:{ids:item.id,element:style.element}}).success(function (resp, status, headers, config) {
                        if (resp.code === 0) {
                            style.data.splice(style.data.indexOf(item),1);
                            msg("删除成功!");
                        } else {
                            alert(resp.msg);
                        }
                    })
                });
            }
            function checkScales(style){
                var numList =[];
                for(var i =0;i<style.data.length;i++){
                    var scale = style.data[i].scale;
                    if(style.data[i].copy){
                        scale = style.data[i].copy.scale;
                    }
                    if(!/^\d+,\d+$/.test(scale)){
                        alert("请检查级别："+scale);
                        return false;
                    }
                    var nums = scale.split(",");
                    var from = parseInt(nums[0]);
                    var to = parseInt(nums[1]);
                    if(from>to||from<0||to>20){
                        alert("请检查级别："+scale);
                        return false;
                    }
                    if(numList.indexOf(from)>-1||numList.indexOf(to)>-1){
                        alert("请检查级别："+scale);
                        return false;
                    }
                    while(from <= to){
                        numList.push(from)
                        from ++;
                    }
                }
                return true;
            }

            $scope.combineRules = function (element,style) {
                if(!checkScales(style)){
                    return;
                }
                var modal = $uibModal.open({
                    animation: false,
                    size:'lg',
                    templateUrl: 'view/instance/ruleSplit.modal.html',
                    controller: 'ruleSplitModalCtrl'
                    ,resolve: {style: function(){return style},instanceId:function(){return $scope.curInstance.id}}
                });
                modal.result.then(function () {
                    $scope.queryRule($scope.curInstance.id,element,style);
                }, function () {
                    console.info('Modal dismissed at: ' + new Date());
                });
            }
            $scope.queryRule = function(instanceId,element,style){
                var search = {currentPage:1,pageSize:10000,instanceId:instanceId,element:element.id,styleTypeId:style.id}
                fac.getPageResult("../rule/list",search,function(resp){
                    style.data = resp.data;
                });
            }

            function findRules(e){
                if(!$scope.curInstance){
                    return;
                }
                $scope.curInstance.curElement = e;
                if(!e.promiss){
                    var deferred = $q.defer();
                    getRequiredPromises(e).then(function(){
                        $http.get("../styleType/listByElement?element="+e.id+"&instanceId="+$scope.curInstance.id).success(function(resp){
                            if(resp.code == 0){
                                e.styles = [];
                                var styles = resp.data;

                                var search = {currentPage:1,pageSize:10000,instanceId:$scope.curInstance.id,element:e.id}

                                fac.getPageResult("../rule/list",search,function(resp){
                                    e.ruleList = resp.data;
                                    styles.forEach(function(style){
                                        style.data = resp.data.filter(function(n){return n.styleTypeId == style.id })
                                    })
                                    styles = styles.sort(function(a,b){
                                        if(a.data.length >0 &&  b.data.length>0){
                                            return 1;
                                        }else if(a.data.length>b.data.length){
                                            return -1;
                                        }else if(b.data.length>a.data.length){
                                            return 1;
                                        }else {
                                            return 0;
                                        }
                                    })

                                    e.rowStyles = styles;
                                    fac.localSplitData(e.rowStyles,e.pageModel,function(pageModel){
                                        e.pageModel = pageModel;
                                        e.styles =pageModel.data;
                                    });

                                    /*if(styles.length<=3){
                                        e.styles = styles;
                                    }else{
                                        e.styles.push(styles[0]);
                                        e.styles.push(styles[1]);
                                        e.styles.push(styles[2]);

                                        var i = 0;
                                        $interval(function () {
                                            e.styles.push(styles[3+i]);
                                            i++;
                                        },30,styles.length-3)
                                    }*/

                                    deferred.resolve();
                                });
                            }
                        })
                    })
                    e.promiss = deferred.promise;
                }
                return e.promiss;
            }

            function findDicts(e){
                if(!e.promiss){
                    var deferred = $q.defer();
                    var search = {currentPage:1,pageSize:10000,instanceId:$scope.curInstance.id,dictType:e.id}
                    fac.getPageResult("../dict/list",search,function(resp){
                        e.data = resp.data;
                        deferred.resolve(resp.data);
                    });
                    e.promiss = deferred.promise;
                }
                /*if(!e.data){

                }*/
                return e.promiss;
            }

            $scope.findRules = function(e){
                findRules(e,1);
            };
            if($scope.dict){

                $scope.dict.showAll=true;
                $scope.dict.pageModel = {currentPage:1,pageSize:10}
                $scope.dict.search={};
            }

            $scope.find = function(currentPage){
                $.extend($scope.dict.search,{currentPage:currentPage||$scope.dict.pageModel.currentPage||1,pageSize:$scope.dict.pageModel.pageSize||10});
                fac.localSplitData($scope.dict.rowStyles,$scope.dict.search,function(pageModel){
                    $scope.dict.pageModel = pageModel;
                    $scope.dict.styles =pageModel.data;
                });
            }

            $scope.localFind = function(currentPage){
                var dict = $scope.curInstance.curElement;
                $.extend(dict.search,{currentPage:currentPage||dict.pageModel.currentPage||1,pageSize:dict.pageModel.pageSize||10});
                fac.localSplitData(dict.rowStyles,dict.search,function(pageModel){
                    dict.pageModel = pageModel;
                    dict.styles =pageModel.data;
                });
            }


        $scope.toggleShow =function(element){
            element.showAll = !element.showAll;
            /*curInstance.

            $http.get("../callUser/toggleLock?id="+item.id).success(function(resp){
                if(resp.code ==0){
                    alert("操作成功!",id)
                }else{
                    alert("操作失败!",id)
                    item.isEnabled = item.isEnabled^3;
                }
            })*/
        }

            $scope.findDicts = function(e){
                findDicts(e);
            };

            $scope.initImage = function(){
                $scope.$broadcast("initImage");
            }

            //获取样式依赖的样式 （点，线，箭头 依赖 文本样式，文本样式依赖颜色和字体）
            function getRequiredStylePromise(instance,ele){
                var listPromises = [];
                if(['point','line','arrow'].indexOf(ele.id)>-1){
                    listPromises.push(findRules(getElement(instance,'text')));
                }
                return listPromises;
            }

            function getElement(instance,eleId){
                return instance.elementList.find(function(n){return n.id == eleId})
            }

            function getDictType(instance,dictId){
                return instance.dictTypeList.find(function(n){return n.id == dictId})
            }

            //获取样式依赖的函数
            function getRequiredDictPromise(instance,ele){
                var listPromises = [];
                switch (ele.id){
                    case "point":
                        listPromises.push(findDicts(getDictType(instance,"font")));
                        listPromises.push(findDicts(getDictType(instance,"fontSize")));
                        listPromises.push(findDicts(getDictType(instance,"point")));
                        break;
                    case "line":
                        listPromises.push(findDicts(getDictType(instance,"line")));
                        listPromises.push(findDicts(getDictType(instance,"fontSize")));
                        listPromises.push(findDicts(getDictType(instance,"font")));
                        listPromises.push(findDicts(getDictType(instance,"dashLine")));
                        break;
                    case "polygon":
                        listPromises.push(findDicts(getDictType(instance,"polygon")));
                        break;
                    case "building":
                        listPromises.push(findDicts(getDictType(instance,"building")));
                        break;
                    case "arrow":
                        listPromises.push(findDicts(getDictType(instance,"arrow")));
                        break;
                    case "roadSign":
                        listPromises.push(findDicts(getDictType(instance,"font")));
                        listPromises.push(findDicts(getDictType(instance,"fontSize")));
                        listPromises.push(findDicts(getDictType(instance,"roadSign")));
                        break;
                }
                return listPromises;
            }

            function getRequiredPromises(ele){
                var listPromises = [];
                // listPromises.push.apply(listPromises,getRequiredStylePromise($scope.curInstance,ele));
                listPromises.push.apply(listPromises,getRequiredDictPromise($scope.curInstance,ele));
                return $q.all(listPromises);
            }
    });
    app.directive("rulePoint", function () {
        return {
            restrict: "E",
            scope: {dict:"<?"},
            templateUrl: 'view/instance/rule_point.html',
            controller: 'ruleCtrl'
        };
    });

    app.directive("ruleLine", function () {
        return {
            restrict: "E",
            scope: {dict:"<?"},
            templateUrl: 'view/instance/rule_line.html',
            controller: 'ruleCtrl'
        };
    });
    app.directive("rulePolygon", function () {
        return {
            restrict: "E",
            scope: {dict:"<?"},
            templateUrl: 'view/instance/rule_polygon.html',
            controller: 'ruleCtrl'
        };
    });
    app.directive("ruleBuilding", function () {
        return {
            restrict: "E",
            scope: {dict:"<?"},
            templateUrl: 'view/instance/rule_building.html',
            controller: 'ruleCtrl'
        };
    });
    app.directive("ruleArrow", function () {
        return {
            restrict: "E",
            scope: {dict:"<?"},
            templateUrl: 'view/instance/rule_arrow.html',
            controller: 'ruleCtrl'
        };
    });
    app.directive("ruleRoadSign", function () {
        return {
            restrict: "E",
            scope: {dict:"<?"},
            templateUrl: 'view/instance/rule_roadSign.html',
            controller: 'ruleCtrl'
        };
    });

    app.directive("styleTypeEdit", function ($http) {
        return {
            restrict: "E",
            //replace:true,
            transclude: true,
            scope: {
                styleType: '<?',
                host:'<?',
                field: '<?'
            },
            templateUrl: 'instanceStyleEdit.html',
            controller: function ($scope) {
                $scope.curInstance = $scope.$parent.curInstance;
                $scope.bean = {fieldVal:$scope.host[$scope.field]};

                $scope.showGroupEdit = function(){
                    $scope.styleType.curStyleTypeId = $scope.host.id;
                    if($scope.styleType.popover == $scope.field ){
                        $scope.styleType.popover = undefined;
                    }else{
                        $scope.styleType.popover = $scope.field;
                    }
                }
                $scope.save= function(){
                    $http.get("../styleType/instanceStyleEdit",{params:{instanceId:$scope.curInstance.id,styleTypeId:$scope.host.id,field:$scope.field,fieldVal:$scope.bean.fieldVal}}).success(function(resp){
                        if(resp.code == 0){
                            msg("设置成功！")
                            $scope.host[$scope.field] = $scope.bean.fieldVal;
                            $scope.styleType.popover = undefined;
                        }else{
                            alert(resp.msg);
                        }
                    })
                }
            }
        };
    });



    app.directive("groupEdit", function ($http) {
        return {
            restrict: "E",
            //replace:true,
            transclude: true,
            scope: {
                styleType: '<?',
                host:'<?',
                field: '<?',
                fieldType:'<?',
                arrayDict:'<?',
                objDict:'<?'
            },
            templateUrl: 'groupEdit.html',
            controller: function ($scope) {

                $scope.curInstance = $scope.$parent.curInstance;
                $scope.bean = {field:$scope.field,element:$scope.styleType.id};

                $scope.showGroupEdit = function(){
                    $scope.bean.ruleIds = $scope.styleType.ruleList.reduce(function (ret, n) {
                        n.checked && ret.push(n.id);
                        return ret
                    }, []);
                    if(!$scope.bean.ruleIds.length){
                        return;
                    }
                    if(!$scope.$root.hasPower('style',$scope.curInstance.id)){
                        return;
                    }
                    $scope.styleType.curStyleTypeId = $scope.host.id;
                    if($scope.styleType.popover == $scope.field ){
                        $scope.styleType.popover = undefined;
                    }else{
                        $scope.styleType.popover = $scope.field;
                    }

                }
                $scope.save= function(){
                    $http.post("../rule/groupEdit",$scope.bean).success(function(resp){
                        if(resp.code == 0){
                            $scope.styleType.ruleList.forEach(function(n){
                                if(n.checked){
                                    n[$scope.field] = $scope.bean.fieldVal;
                                }
                            })
                            msg("批量设置成功！")
                            $scope.styleType.popover = undefined;
                        }else{
                            alert(resp.msg);
                        }
                    })
                }
            }
        };
    });

    app.directive("instanceDetail", function ($rootScope, $http,$uibModal,$stateParams,fac, $q,$interval) {
        return {
            restrict: "E",
            scope: {
                curInstance: '<?',
                search:'<?'
            },
            replace:true,
            templateUrl: 'view/instance/instance.detail.html',
            controller:'ruleCtrl'
        };
    });

    app.controller('instanceCtrl', function ($scope,$rootScope, $http,$uibModal,$stateParams,fac, $q) {
        var sceneId = $stateParams.id
        console.log(sceneId);

        $scope.search = {sceneId:sceneId};
        $scope.pageModel = {};
        $rootScope.instanceCache = $rootScope.instanceCache||[];
        console.log($stateParams.id);
     /*   function getParam(url,name) {
            return url.match(new RegExp('[?#&]?' + name + '=([^?#&]+)', 'i')) ? RegExp.$1 : '';
        }*/

        $scope.find = function(pageNo){
            $.extend($scope.search,{currentPage:pageNo||$scope.pageModel.currentPage||1,pageSize:$scope.pageModel.pageSize||200});
            $scope.search.pageIndex = $scope.search.currentPage-1;
            fac.getPageResult("../instance/list",$scope.search,function(data){
                $scope.pageModel = data;
            });
        };
        $scope.find(1);

        $scope.$on("refreshStyleType",function(){
            $scope.find(1);
        })
        $scope.$on("closeInstanceDetail",function(){
            $scope.search.curInstance = undefined;
        })


      /*  $scope.addXml = function () {
            fac.upload({ url: "/style/uploadXml", accept: "text/xml, application/xml",params:{'sceneId':sceneId} }, function (resp) {
                if (resp.code == 0 ) {
                    $rootScope.elementEnum.forEach(function(n){delete n.pageModel});
                    msg("导入成功！")
                } else {
                    alert(resp.msg);
                }
            })
        }*/
/*        $scope.listStyles = function(TextSymbolizer){
            return  $scope.curInstance.elementList.find(function(n){return n.id == 'text' })
                .styles.filter(function(m){return m.data.find(function(l){ return l.texttype == TextSymbolizer})})
        }*/
   /*     $scope.setCurTextStyle = function(item,textName){
            if($scope.curTextStyle && $scope.curTextStyle.ruleId == item.id){
                delete $scope.curTextStyle.ruleId;
                return;
            }
            var textStyleList = $scope.curInstance.elementList.find(function(n){return n.id == 'text'}).styles;
            $scope.curTextStyle =  textStyleList.find(function(n){return n.id == textName});
            $scope.curTextStyle.ruleId = item.id;
        }*/





        //添加与保存instance
        $scope.showEditModal = function(item,copy){
            var tt = angular.extend({},item);
            tt.copy = copy ;
            var modal = $uibModal.open({
                animation: false,
                size:'',
                templateUrl: 'view/instance/instance.modal.html',
                controller: 'instanceModalCtrl'
                ,resolve: {item: tt}
            });
            modal.result.then(function () {
                $scope.find();
            }, function () {
                console.info('Modal dismissed at: ' + new Date());
            });
        };

        $scope.showDetail = function(item){
            $scope.search.curInstance = item;
            if(!item.elementList){
                item.elementList = $.extend(true,[],$rootScope.elementList);
                item.dictTypeList = $.extend(true,[],$rootScope.dictTypeList);
            }
            if(!$rootScope.instanceCache.includes(item)){
                $rootScope.instanceCache.push(item);
            }
            //$scope.search.showOn = true;
        };
        //删除
        $scope.del = function(item){
            confirm("确认删除该样式吗？",function(){
                $http.get("../instance/del?ids="+item.id).success(function(resp){
                    if(resp.code === 0){
                        $scope.find();
                    }else{
                        alert(resp.msg);
                    }
                })
            });
        }

        $scope.downloadXml = function(item){
            confirm("确认下载样式 " + item.name + " 的xml吗?",function(){
                try{
                    var elemIF = document.createElement("iframe");
                    elemIF.src = "../release/downloadXml?instanceId="+item.id;
                    elemIF.style.display = "none";
                    document.body.appendChild(elemIF);
                }catch(e){

                }
            })
        }
    });


    app.controller('instanceModalCtrl', function($scope,$http,$uibModalInstance,fac,item) {
        if(item.copy){
           delete item.name;
        }
        if(item.baseMapStyle){
            try{
                $scope.keyValues = JSON.parse(item.baseMapStyle);
            }catch(e){
                $scope.keyValues = [];
            }
        }else{
            $scope.keyValues = [];
        }
        $scope.item = item;

        $scope.add = function(){
            $scope.keyValues.push('key="" value=""');
        }
        $scope.save = function (form) {
            form.$setSubmitted(true);
            if (!form.$valid) {
                return;
            }
            item.baseMapStyle = JSON.stringify($scope.keyValues);
            var url = item.copy?"/instance/copy":"/instance/update";
            var message = item.id?"保存成功!":"复制成功！";
            $http.post(url, item).success(function (data, status, headers, config) {
                if (data.code === 0) {
                    $uibModalInstance.close();
                    msg(message);
                } else {
                    alert(data.msg);
                }
            })
        }
    });

    app.controller('ruleSplitModalCtrl', function($scope,$http,$uibModalInstance,fac,style,instanceId) {

        $scope.style = style;
        style.data.sort(function(a,b){return a.scale.split(",")[0]-b.scale.split(",")[0]});
        //{no:1,can:true},{no:2,can:true},{no:3,can:true},{no:4,can:true},{no:5,can:true},{no:6,can:true},{no:7,can:true},{no:8,can:true}
        $scope.scissors = []
        for(var i =0;i<style.data.length;i++){
            var nums = style.data[i].scale.split(",");
            var from = parseInt(nums[0]);
            var to = parseInt(nums[1]);
            while(from < to){
                    $scope.scissors.push({ruleId:style.data[i].id,no:from,can:true})
                from ++;
            }
            var scissor = {ruleId:style.data[i].id,no:to,cut:true};
            if(i==style.data.length-1){
                scissor.cut = false;
            }else if( fac.compare(style.data[i],style.data[i+1])){
                scissor.can = true;
            }else{
                scissor.can = false;
            }
            $scope.scissors.push(scissor)
        }
        $scope.scales = style.data.map(function(n){return {ruleId:n.id,from:n.scale.split(",")[0],to:n.scale.split(",")[1]}});

        $scope.caluCut = function(scissor){
            scissor.cut=!scissor.cut;
            getRet();
        }
        function getRet () {
            $scope.scales = [];
            var item = {};
            $scope.scissors.forEach(function(n,i){
                if(item.from === undefined ){
                    item.ruleId = n.ruleId;
                    item.from = n.no;
                    if(n.cut||i == $scope.scissors.length -1){
                        item.to = n.no;
                        $scope.scales.push(item);
                        item = {}
                    }
                }else if(item.from !== undefined && (n.cut||i == $scope.scissors.length -1)){
                     item.to = n.no;
                     $scope.scales.push(item);
                     item = {}
                }
            })

  /*          var cuts = $scope.scissors.filter(function(n){return n.cut});
            var from = 0;
            cuts.forEach(function(n){
                $scope.scales.push({from:from,to:n.no,ruleId:n.ruleId});
                from = n.no+1;
            })
            var lastScissor = $scope.scissors[$scope.scissors.length-1];
            $scope.scales.push({from:from,to:lastScissor.no,ruleId:lastScissor.ruleId});*/
        }

        $scope.save = function () {
            var combineBean = {instanceId:instanceId,element:style.element,styleTypeId:style.id,rules:$scope.scales}
            $http.post("../rule/combine", combineBean).success(function (resp, status, headers, config) {
                if (resp.code === 0) {
                    $uibModalInstance.close();
                    msg("保存成功!");
                } else {
                    alert(resp.msg);
                }
            })
        }
    });

    app.controller('instanceIconCtrl', function($scope,$rootScope,$http,fac) {
        $scope.iconTypes=$.extend([],$rootScope.iconTypeEnum,true);

        var instanceId ;
        function find (pageNo,iconType){
            iconType.search = iconType.search||{instanceId:instanceId};
            iconType.search.typeId = iconType.id;
            $.extend(iconType.search,{currentPage:pageNo||iconType.pageModel.currentPage||1,pageSize:iconType.pageModel.pageSize||20000});
            fac.getPageResult("../icon/listSprite",iconType.search,function(data){
                iconType.pageModel = data;
                $(".iconScroll").css("height",window.innerHeight-190);
            });
        };

        $scope.findImage = function(pageNo){
            find(pageNo,$scope.iconTypes[0]);
        }
        $scope.findSprite = function(pageNO){
            find(pageNo,$scope.iconTypes[1]);
        }

        function initImage(){
            instanceId = $scope.$parent.curInstance.id
            $scope.iconTypes.forEach(function(n){
                n.pageModel = {};
                find(1,n);
            })
        }

        $scope.$on("initImage",function(){
            initImage();
        });


        $scope.refreshInstanceIcon = function(instanceId){
            $http.get("../instance/refreshInstanceIcon?instanceId="+instanceId).success(function(resp){
                if(resp.code == 0){
                    initImage();
                }
            })
        }


        $scope.save = function (form) {
            form.$setSubmitted(true);
            if (!form.$valid) {
                return;
            }
            var url = item.copy?"/instance/copy":"/instance/update";
            var message = item.id?"保存成功!":"复制成功！";
            $http.post(url, item).success(function (data, status, headers, config) {
                if (data.code === 0) {
                    $uibModalInstance.close();
                    msg(message);
                } else {
                    alert(data.msg);
                }
            })
        }
    });

    app.controller('styleCopyModalCtrl', function($scope,$http,$uibModalInstance,$q,fac,style,dict,curInstance) {
        $scope.style = style;
        $scope.dict = dict;
        $scope.curInstance = curInstance;
        $scope.temp = {style:style};
        $scope.item = {element:dict.id};
        $scope.findInstance = function(pageNo,val){
            if(!$scope.item.sceneId){
                return;
            }
            var deferred = $q.defer()
            var param = {sceneId:$scope.item.sceneId,name:val};
            $.extend(param,{currentPage:pageNo||1,pageSize:10});
            fac.getPageResult("../instance/list",param,function(pageModel){
                deferred.resolve(pageModel.data);
            });
            return deferred.promise;
        };

        $scope.filterStyle = function(val){

            var deferred = $q.defer()
            var param = {name:val};
            $.extend(param,{currentPage:pageNo||1,pageSize:10});
            fac.getPageResult("../instance/list",param,function(pageModel){
                deferred.resolve(pageModel.data);
            });
            return deferred.promise;
        };

        $scope.save = function (form,item) {
            form.$setSubmitted(true);
            if (!form.$valid) {
                return;
            }
            if($scope.temp.instance.id == curInstance.id && $scope.temp.style.id == style.id){
                alert("不能复制给本样式的同样式类型！");
                return;
            }
            item.styleId = $scope.temp.style.id;
            item.instanceId = $scope.temp.instance.id;
            item.oldInstanceId = curInstance.id;
            item.ruleIds = style.data.reduce(function (ret, n) {  ret.push(n.id); return ret     }, []);

            $http.get("../rule/copyStyle", {params:item}).success(function (resp, status, headers, config) {
                if (resp.code === 0) {
                    $uibModalInstance.close(item);
                    msg("保存成功!");
                } else {
                    alert(resp.msg);
                }
            })
        }
    });

})();



/*  app.controller('fontModalCtrl', function($scope,$http,$uibModalInstance,item) {
     $scope.item = item;
     $scope.save = function (form) {
         form.$setSubmitted(true);
         if (!form.$valid) {
             return;
         }
         $http.post("../dict/saveFont", item).success(function (resp, status, headers, config) {
             if (resp.code === 0) {
                 $uibModalInstance.close(resp.data);
                 msg("保存成功!");
             } else {
                 alert(resp.msg);
             }
         })
     }
 });

 app.controller('dashLineModalCtrl', function($scope,$http,$uibModalInstance,item) {
     $scope.item = item;
     $scope.save = function (form) {
         form.$setSubmitted(true);
         if (!form.$valid) {
             return;
         }
         $http.post("../dict/saveDashLine", item).success(function (resp, status, headers, config) {
             if (resp.code === 0) {
                 $uibModalInstance.close(resp.data);
                 msg("保存成功!");
             } else {
                 alert(resp.msg);
             }
         })
     }
 });*/


/*$scope.splitRule = function (style,item) {
    confirm("确认删除该样式规则吗？",function(){
        $http.get("../rule/del", {params:{ids:item.id,element:style.element}}).success(function (resp, status, headers, config) {
            if (resp.code === 0) {
                style.data.splice(style.data.indexOf(item),1);
                msg("删除成功!");
            } else {
                alert(resp.msg);
            }
        })
    });
}*/
/* $scope.showColorModal = function(item,type){

     var modal = $uibModal.open({
         animation: false,
         size:'',
         templateUrl: 'view/instance/color.modal.html',
         controller: 'colorModalCtrl'
         ,resolve: {item: angular.extend({},item)}
     });
     modal.result.then(function (color) {
         if(item.id){
             angular.extend(item,color);
         }else{
             type.data = type.data||[];
             type.data.splice(0,0,color);
         }
        // $scope.find();
     }, function () {
         console.info('Modal dismissed at: ' + new Date());
     });
 };

 $scope.showFontModal = function(item,type){
     var modal = $uibModal.open({
         animation: false,
         size:'',
         templateUrl: 'view/instance/font.modal.html',
         controller: 'fontModalCtrl'
         ,resolve: {item: angular.extend({},item)}
     });
     modal.result.then(function (font) {
         if(item.id){
             angular.extend(item,font);
         }else{
             type.data = type.data||[];
             type.data.splice(0,0,font);
         }
         // $scope.find();
     }, function () {
         console.info('Modal dismissed at: ' + new Date());
     });
 };

 $scope.showDashLineModal = function(item,type){
     var modal = $uibModal.open({
         animation: false,
         size:'',
         templateUrl: 'view/instance/dashLine.modal.html',
         controller: 'dashLineModalCtrl'
         ,resolve: {item: angular.extend({},item)}
     });
     modal.result.then(function (dashLine) {
         if(item.id){
             angular.extend(item,dashLine);
         }else{
             type.data = type.data||[];
             type.data.splice(0,0,dashLine);
         }
         // $scope.find();
     }, function () {
         console.info('Modal dismissed at: ' + new Date());
     });
 };
*/